package com.hefan.api.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.common.meta.SmsCodeTypeEnum;
import com.cat.tiger.util.CollectionUtils;
import com.hefan.api.bean.LoginUserVo;
import com.hefan.api.service.SmsLocalService;
import com.hefan.api.service.UserLocalService;
import com.hefan.api.util.GeocoderUtil;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;
import com.hefan.user.bean.WebUser;
import com.hefan.user.bean.WebUserIdentity;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lxw on 2016/9/29.
 */
@Controller
@RequestMapping("/v1/user")
public class UserController {

    public static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private SmsLocalService smsLocalService;
    @Resource
    private UserLocalService userLocalService;

    /**
     * 绑定(变更)手机号|第三方账号
     * @param request
     * @return
     */
    @RequestMapping("/accountBind")
    @ResponseBody
    public String accountBindSet(HttpServletRequest request) {
        //Profiler profiler = new Profiler("accountBindSet--start");
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            LoginUserVo loginUserVo = HttpUtils.initParam(request, LoginUserVo.class);
            if (loginUserVo == null || StringUtils.isBlank(loginUserVo.getUserId()) || StringUtils.isBlank(loginUserVo.getOpenid()) || loginUserVo.getThirdType() == 0) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
            }
            if (loginUserVo.getThirdType() < 1 || loginUserVo.getThirdType() > 4) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
            }
            if (loginUserVo.getThirdType() == 4) { //绑定手机号时需要短信验证码
                if (StringUtils.isBlank(loginUserVo.getMsCode())) {
                    return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
                }
                //检查短信验证码
                //profiler.start("accountBindSet--checkSmsCode--runTime@@");
                resultBean = smsLocalService.checkSmsCode(SmsCodeTypeEnum.CHANGE_SMS_CODE_TYPE.getType(), loginUserVo.getOpenid(), loginUserVo.getMsCode());
                if (resultBean.getCode() != ResultCode.SUCCESS.get_code()) {
                    return JSON.toJSONString(resultBean);
                }
            }
            //绑定账号
            //profiler.start("accountBindSet--accountSafeOpreate--runTime@@");
            resultBean = userLocalService.accountSafeOpreate(loginUserVo.getUserId(), 1, loginUserVo);
        }catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        } finally {
            //profiler.stop().print();
        }
        return  JSON.toJSONString(resultBean);
    }

    /**
     * 解绑第三方账号
     * @param request
     * @return
     */
    @RequestMapping("/accountUnBind")
    @ResponseBody
    public String accountUnBindSet(HttpServletRequest request) {
        //Profiler profiler = new Profiler("accountUnBindSet--start");
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            LoginUserVo loginUserVo = HttpUtils.initParam(request,LoginUserVo.class);
            if(loginUserVo == null || StringUtils.isBlank(loginUserVo.getUserId())) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
            }
            if(loginUserVo.getThirdType()<1 || loginUserVo.getThirdType()>3) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
            }
            WebUser webUser = userLocalService.getWebUserByUserId(loginUserVo.getUserId());
            if(webUser == null) {
                return JSON.toJSONString(new ResultBean(ResultCode.UserNotFound, null));
            }
            boolean isUnBind = true;
            switch (loginUserVo.getThirdType()) {
                case 1 :
                    if(StringUtils.isBlank(webUser.getMobile()) && StringUtils.isBlank(webUser.getOpenidWx())  && StringUtils.isBlank(webUser.getUnionidWx()) && StringUtils.isBlank(webUser.getOpenidQq())) isUnBind=false;
                    break;
                case 2 :
                    if(StringUtils.isBlank(webUser.getMobile()) && StringUtils.isBlank(webUser.getOpenidWb()) && StringUtils.isBlank(webUser.getOpenidQq())) isUnBind=false;
                    break;
                case 3 :
                    if(StringUtils.isBlank(webUser.getMobile()) && StringUtils.isBlank(webUser.getOpenidWb())  && StringUtils.isBlank(webUser.getUnionidWx()) && StringUtils.isBlank(webUser.getOpenidWx())) isUnBind=false;
                    break;
                default:
            }
            if(!isUnBind) {  //只有一个绑定信息，不能进行解绑
                return JSON.toJSONString(new ResultBean(ResultCode.AccountOnlayFial, null));
            }
            //解绑账号
            loginUserVo.setOpenid("");
            resultBean = userLocalService.accountSafeOpreate(loginUserVo.getUserId(), 2,loginUserVo);
        }catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        } finally {
            //profiler.stop().print();
        }
        return  JSON.toJSONString(resultBean);
    }

    /**
     * 变更手机号短信验证码验证
     * @param request
     * @return
     */
    @RequestMapping("/changeSmsCodeCheck")
    @ResponseBody
    public String changeMobileMsCodeCheck(HttpServletRequest request) {
        //Profiler profiler = new Profiler("changeMobileMsCodeCheck--start");
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            LoginUserVo loginUserVo = HttpUtils.initParam(request,LoginUserVo.class);
            if(loginUserVo == null || StringUtils.isBlank(loginUserVo.getMobile()) || StringUtils.isBlank(loginUserVo.getMsCode()) ) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
            }
            //检查短信验证码
            resultBean = smsLocalService.checkSmsCode(SmsCodeTypeEnum.CHANGE_SMS_CODE_TYPE.getType(),loginUserVo.getMobile(),loginUserVo.getMsCode());
        }catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        } finally {
            //profiler.stop().print();
        }
        return JSON.toJSONString(resultBean);
    }

    /**
     * 编辑个人信息
     *
     * @return
     */
    @RequestMapping("/editUserInfo")
    @ResponseBody
    public String editUserInfo(HttpServletRequest request) {
        //Profiler profiler = new Profiler("editUserInfo--start");
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS, null);
        try {
            WebUser webUser = HttpUtils.initParam(request, WebUser.class);
            if (webUser == null || StringUtils.isBlank(webUser.getUserId())) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException));
            }
            if (StringUtils.isBlank(webUser.getHeadImg()) && StringUtils.isBlank(webUser.getNickName()) && StringUtils.isBlank(webUser.getStar()) && StringUtils.isBlank(webUser.getFeeling())
                && webUser.getPersonSign() == null && StringUtils.isBlank(webUser.getProvince()) && webUser.getJob() == null && StringUtils.isBlank(webUser.getCity()) && StringUtils
                .isBlank(webUser.getBackGround()) && webUser.getBirthday() == null && webUser.getSex() == null && webUser.getAge() == null) {
                return JSON.toJSONString(new ResultBean(ResultCode.ParamException));
            }
            //更新用户基本信息
            resultBean = userLocalService.updateUserBaseInfo(webUser);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS, null));
        } finally {
            //profiler.stop().print();
        }
        return JSON.toJSONString(resultBean);
    }

    /**
     * 获取系统配置的银行信息
     */
    @RequestMapping("/findSysBankList")
    @ResponseBody
    public String findSysBankList() {
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            resultBean = userLocalService.findSysBankList();
        }catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        }
        return JSON.toJSONString(resultBean);
    }


    /**
     * 用户申请主播认证申请提交
     * @param request
     * @return
     */
    @RequestMapping("/userIdentitySubmit")
    @ResponseBody
    public String userIdentitySubmit(HttpServletRequest request) {
        //Profiler profiler = new Profiler("userIdentitySubmit--start");
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            WebUserIdentity webUserIdentity = HttpUtils.initParam(request,WebUserIdentity.class);
            if(webUserIdentity == null || StringUtils.isBlank(webUserIdentity.getUserId())
                    || StringUtils.isBlank(webUserIdentity.getMsCode()) ||StringUtils.isBlank(webUserIdentity.getContactPhone())
                    || StringUtils.isBlank(webUserIdentity.getRealName()) || StringUtils.isBlank(webUserIdentity.getPersonId())
                    || StringUtils.isBlank(webUserIdentity.getLifePhone1()) || StringUtils.isBlank(webUserIdentity.getLifePhone2())
                    || StringUtils.isBlank(webUserIdentity.getLifePhone3()) || webUserIdentity.getHistory() == null) {
                return  JSON.toJSONString(new ResultBean(ResultCode.ParamException,null));
            }
            if(webUserIdentity.getHistory() == 1) { //有主播经历时需要填写原直播平台和直播id号
                if(StringUtils.isBlank(webUserIdentity.getPlatForm()) ||  StringUtils.isBlank(webUserIdentity.getLiveId())) {
                    return  JSON.toJSONString(new ResultBean(ResultCode.ParamException,null));
                }
            }
            //主播申请验证码_检查短信验证码
            //profiler.start("userIdentitySubmit--checkSmsCode--runTime@@");
            resultBean = smsLocalService.checkSmsCode(SmsCodeTypeEnum.IDENTITY_SMS_CODE_TYPE.getType(),webUserIdentity.getContactPhone(),webUserIdentity.getMsCode());
            if(resultBean.getCode() != ResultCode.SUCCESS.get_code()) {
                return JSON.toJSONString(resultBean);
            }
            //用户申请主播注册保存
            //profiler.start("userIdentitySubmit--userIndentitySubmit--runTime@@");
            resultBean = userLocalService.userIndentitySubmit(webUserIdentity);
        }catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        } finally {
            //profiler.stop().print();
        }
        return JSON.toJSONString(resultBean);
    }
    
    /**
     * 上传用户定位信息
     * @param req
     * @param location
     * @param userId
     * @return
     */
    @RequestMapping(value="/uploadLocation",method=RequestMethod.GET)
    @ResponseBody
    public String uploadLocation(HttpServletRequest req,String location,String userId){
        //Profiler profiler = new Profiler("uploadLocation--start");
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS,null);
        try {
            Map<String,Object> map = HttpUtils.initParam(req, Map.class);
            userId = MapUtils.getStrValue(map, "userId", "");
            location = MapUtils.getStrValue(map, "location", "");
            if(StringUtils.isEmpty(userId) || StringUtils.isEmpty(location) ){
                resultBean.setCode(ResultCode.ParamException.get_code());
                resultBean.setMsg(ResultCode.ParamException.getMsg());
            }else{
                try {
                    JSONObject jsonObj = 	JSONObject.parseObject(GeocoderUtil.getCityByLocation(location));
                    if(jsonObj.getInteger("status")==0){
                        String gpsLocation = jsonObj.getString("city");
                        userLocalService.updateWebUserLocation(userId,gpsLocation);
                        resultBean.setCode(ResultCode.SUCCESS.get_code());
                        resultBean.setMsg(ResultCode.SUCCESS.getMsg());
                        resultBean.setData(gpsLocation);
                    }else{
                    	resultBean.setCode(ResultCode.UNSUCCESS.get_code());
                        resultBean.setMsg("status:"+jsonObj.getInteger("status")+"err:"+jsonObj.getString("err"));
                        logger.error("status:"+jsonObj.getInteger("status")+"err:"+jsonObj.getString("err"));
                    }
                } catch (Exception e) {
                    resultBean.setCode(ResultCode.UNSUCCESS.get_code());
                    resultBean.setMsg(ResultCode.UNSUCCESS.getMsg());
                }
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        } finally {
            //profiler.stop().print();
        }
        return JSON.toJSONString(resultBean);
    }
    
    
    /**
     * 推荐明星俱乐部
     * @return
     */
    @RequestMapping(value="/recommendStarClub",method=RequestMethod.GET)
    @ResponseBody
    public String recommendStarClub(HttpServletRequest req,Integer pageNo,Integer pageSize,String userId){
    	ResultBean resultBean = new ResultBean();
    	Map<String,Object> map = HttpUtils.initParam(req, Map.class);
    	userId = MapUtils.getStrValue(map, "userId", "");
		pageNo = MapUtils.getIntValue(map, "pageNo", 1);
		pageSize = MapUtils.getIntValue(map, "pageSize", 5);
		
		if(StringUtils.isEmpty(userId)){
            resultBean.setCode(ResultCode.ParamException.get_code());
            resultBean.setMsg(ResultCode.ParamException.getMsg());
        }else{
        	try {
        		Page page = new Page();
				page.setPageNo(pageNo);
				page.setPageSize(pageSize);
				page.setOrderBy("isWatched");
				page.setOrder(Page.ASC);
				page = userLocalService.recommendStarClub(page,userId);
				resultBean.setData(page);
				resultBean.setCode(ResultCode.SUCCESS.get_code());
				resultBean.setMsg(ResultCode.SUCCESS.getMsg());
			} catch (Exception e) {
				e.printStackTrace();
				resultBean.setCode(ResultCode.UNSUCCESS.get_code());
                resultBean.setMsg(ResultCode.UNSUCCESS.getMsg());
			}
        }
    	return JSON.toJSONString(resultBean);
    }

    /**
     * app编辑个人简介
     * @param request
     */
    @RequestMapping(value="/modifyPersonalProfile")
    @ResponseBody
    public String modifyPersonalProfile(HttpServletRequest request) {
        //Profiler profiler = new Profiler("modifyPersonalProfile--start");
        ResultBean resultBean = new ResultBean(ResultCode.SUCCESS);
        try {
            Map paramsMap = HttpUtils.initParam(request,HashMap.class);
            if(CollectionUtils.isEmpty(paramsMap)
                    || !paramsMap.containsKey("userId")  || !paramsMap.containsKey("nickName")
                    || !paramsMap.containsKey("bgimg") || !paramsMap.containsKey("profiles")
                    || StringUtils.isBlank(String.valueOf(paramsMap.get("userId")))
                    || StringUtils.isBlank(String.valueOf(paramsMap.get("nickName")))
                    || StringUtils.isBlank(String.valueOf(paramsMap.get("bgimg")))
                    || StringUtils.isBlank(String.valueOf(paramsMap.get("profiles")))) {
                return  JSON.toJSONString(new ResultBean(ResultCode.ParamException));
            }
            //修改用户个人简介信息
            resultBean = userLocalService.modifyUserPersionalProfile(paramsMap);
        }catch (Exception e) {
            logger.error(e.getMessage());
            return JSON.toJSONString(new ResultBean(ResultCode.UNSUCCESS,null));
        } finally {
            //profiler.stop().print();
        }
        return JSON.toJSONString(resultBean);
    }

}
